package cn.itcast.controller.cargo;

import cn.itcast.controller.BaseController;
import cn.itcast.domain.cargo.Contract;
import cn.itcast.domain.cargo.ContractExample;
import cn.itcast.domain.system.User;
import cn.itcast.domain.vo.ContractProductVo;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.utils.DownloadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/cargo/contract")
public class ContractController extends BaseController{
    @Reference
    private ContractService contractService;
    @Autowired
    private DownloadUtil downloadUtil;
    @RequestMapping(value = "/list",name = "合同展示界面")
    public String findAll(@RequestParam(value = "page",defaultValue = "1") int pageNum, @RequestParam(defaultValue = "5") int pages){
        ContractExample contractExample = new ContractExample();
        contractExample.setOrderByClause("create_time desc");
        ContractExample.Criteria criteria = contractExample.createCriteria();
        criteria.andCompanyIdEqualTo(getCompanyId());
        User user = getUser();//登录人
        Integer degree = user.getDegree();
        if(degree==4){
            criteria.andCreateByEqualTo(user.getId());
        }else if(degree==3){
            criteria.andCreateDeptEqualTo(user.getDeptId());
        }else if(degree==2){
            criteria.andCreateDeptLike(user.getDeptId()+"%");
        }
        contractExample.setOrderByClause("create_time desc");
        PageInfo pageInfo = contractService.findAll(contractExample, pageNum, pages);
        request.setAttribute("page",pageInfo);
        return "cargo/contract/contract-list";
    }
    @RequestMapping(value = "/toAdd",name = "跳转到添加添加界面")
    public String toAdd(){
        return "cargo/contract/contract-add";
    }
    @RequestMapping(value = "/edit",name = "新建和编辑界面")
    public String adit(Contract contract){
        if(StringUtils.isBlank(contract.getId())) {
            contract.setId(UUID.randomUUID().toString());
            contract.setCompanyId(getCompanyId());
            contract.setCompanyName(getCompanyName());
            contract.setState(0);
            contract.setCreateTime(new Date());
            contract.setCreateBy(getUser().getId());
            contract.setCreateDept(getUser().getDeptId());
            contractService.save(contract);
        }else {
            contractService.update(contract);
        }
        return "redirect:/cargo/contract/list.do";
    }
    @RequestMapping(value = "/toUpdate",name = "进到更新界面")
    public String toUpdate(String id){
        Contract contract = contractService.findById(id);
        request.setAttribute("contract",contract);
        return "cargo/contract/contract-add";
    }
    @RequestMapping(value = "/delete",name = "删除数据")
    public String delete(String id){
        contractService.delete(id);
        return "redirect:/cargo/contract/list.do";
    }
    @RequestMapping("/submit")
    public String submit(String id){
        Contract con = contractService.findById(id);
        con.setState(1);
        contractService.update(con);
        return "redirect:/cargo/contract/list.do";
    }
    @RequestMapping("/cancel")
    public String cancel(String id){
        Contract contract = contractService.findById(id);
        contract.setState(0);
        contractService.update(contract);
        return "redirect:/cargo/contract/list.do";
    }
    @RequestMapping(value = "/print",name = "打印出货表")
    public String print(){
        return "cargo/print/contract-print";
    }
    //2015-01
    @RequestMapping(value = "/printExcel",name = "导出数据到excel")
    public void printExcel(String inputDate) throws IOException {
        List<ContractProductVo> list=contractService.findByInputDateAndCompanyId(inputDate,getCompanyId());
        XSSFWorkbook workbook = new XSSFWorkbook();
        //开始设置头的样式
        XSSFCellStyle cellStyle = workbook.createCellStyle();
        XSSFFont font = workbook.createFont();
        font.setBold(true);
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 16);
        cellStyle.setFont(font);
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        //结束样式
        XSSFSheet sheet = workbook.createSheet();
        sheet.setColumnWidth(0,4200); //
        sheet.setColumnWidth(1,26*256); //
        sheet.setColumnWidth(2,16*256); //
        sheet.setColumnWidth(3,26*256); //
        sheet.setColumnWidth(4,16*256); //
        sheet.setColumnWidth(5,16*256); //
        sheet.setColumnWidth(6,16*256); //
        sheet.setColumnWidth(7,16*256); //
        sheet.setColumnWidth(8,16*256); //
        //在上面的一行
        XSSFRow row = sheet.createRow(0);
        for (int i = 0; i <= 8; i++) {
            row.createCell(i);
        }
        row.setHeightInPoints(36);
        sheet.addMergedRegion(new CellRangeAddress(0,0,1,8));
        XSSFCell cell = row.getCell(1);
        cell.setCellValue(inputDate.replaceAll("-0","年").replaceAll("-","年")+"月份出货表");
        cell.setCellStyle(cellStyle);
        //第二行
        String[] title={"客户","合同号","货号","数量","工厂","工厂交期","船期","贸易条款"};
        XSSFRow row1 = sheet.createRow(1);
        row1.setHeightInPoints(26);
        XSSFCellStyle cellStyle1 = workbook.createCellStyle();
        XSSFFont font1 = workbook.createFont();
        font1.setBold(true);
        font1.setFontHeightInPoints((short)12);
        font1.setFontName("黑体");
        cellStyle1.setFont(font1);
        cellStyle1.setAlignment(HorizontalAlignment.CENTER);
        cellStyle1.setVerticalAlignment(VerticalAlignment.CENTER);
        cellStyle1.setBorderTop(BorderStyle.THIN);
        cellStyle1.setBorderLeft(BorderStyle.THIN);
        cellStyle1.setBorderBottom(BorderStyle.THIN);
        cellStyle1.setBorderRight(BorderStyle.THIN);
        for (int i = 1; i <= 8; i++) {
            XSSFCell cell1 = row1.createCell(i);
            cell1.setCellStyle(cellStyle1);
            cell1.setCellValue(title[i-1]);
        }
        //第三行之后
        XSSFRow row2=null;
        XSSFCell cell1=null;
        XSSFCellStyle cellStyle2 = workbook.createCellStyle();
        XSSFFont font2 = workbook.createFont();
        font2.setFontName("Times New Roman");
        font2.setFontHeightInPoints((short)10);

        cellStyle2.setFont(font2);

        cellStyle2.setAlignment(HorizontalAlignment.LEFT);              //横向居左
        cellStyle2.setVerticalAlignment(VerticalAlignment.CENTER);     //纵向居中
        cellStyle2.setBorderTop(BorderStyle.THIN);              //上细线
        cellStyle2.setBorderBottom(BorderStyle.THIN);            //下细线
        cellStyle2.setBorderLeft(BorderStyle.THIN);             //左细线
        cellStyle2.setBorderRight(BorderStyle.THIN);
        for (int i = 0; i < list.size(); i++) {
             row2= sheet.createRow(i + 3);
             row2.setRowStyle(cellStyle2);
             cell1= row2.createCell(1);
            cell1.setCellValue(list.get(i).getCustomName());

            cell1 = row2.createCell(2);
            cell1.setCellValue(list.get(i).getContractNo());

            cell1 = row2.createCell(3);
            cell1.setCellValue(list.get(i).getProductNo());

            cell = row2.createCell(4);
            cell.setCellValue(list.get(i).getCnumber());

            cell = row2.createCell(5);
            cell.setCellValue(list.get(i).getFactoryName());
//            工厂交期	船期	贸易条款
            cell = row2.createCell(6);
            cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(list.get(i).getDeliveryPeriod()));

            cell = row2.createCell(7);
            cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(list.get(i).getShipTime()));

            cell = row2.createCell(8);
            cell.setCellValue(list.get(i).getTradeTerms());
        }
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);
        downloadUtil.download(byteArrayOutputStream,response,"出货表.xlsx");
    }

    @RequestMapping(value = "/printExcel1",name = "使用模板导出数据到excel")
    public void printExcel1(String inputDate) throws IOException {
        List<ContractProductVo> list=contractService.findByInputDateAndCompanyId(inputDate,getCompanyId());
        String realPath = session.getServletContext().getRealPath("/templates/t.xlsx");
        System.out.println(realPath);
        FileInputStream is = new FileInputStream(realPath);
        XSSFWorkbook workbook = new XSSFWorkbook(is);
        XSSFSheet sheetAt = workbook.getSheetAt(0);
        XSSFCell cell = sheetAt.getRow(0).getCell(1);
        cell.setCellValue(inputDate.replaceAll("-0","年").replaceAll("-","年")+"月份出货表");
        //第三行之后
        CellStyle[] cellStyles=new CellStyle[8];
        XSSFRow row = sheetAt.getRow(2);
        for (int i = 0; i < 8; i++) {
            cellStyles[i]=row.getCell(i+1).getCellStyle();
        }
        XSSFRow row2=null;
        XSSFCell cell1=null;
        for (int i = 0; i < list.size(); i++) {
            row2= sheetAt.createRow(i + 3);
            cell1= row2.createCell(1);
            cell1.setCellValue(list.get(i).getCustomName());
            cell1.setCellStyle(cellStyles[0]);

            cell1 = row2.createCell(2);
            cell1.setCellValue(list.get(i).getContractNo());
            cell1.setCellStyle(cellStyles[1]);

            cell1 = row2.createCell(3);
            cell1.setCellValue(list.get(i).getProductNo());
            cell1.setCellStyle(cellStyles[2]);

            cell1 = row2.createCell(4);
            cell1.setCellValue(list.get(i).getCnumber());
            cell1.setCellStyle(cellStyles[3]);

            cell1 = row2.createCell(5);
            cell1.setCellValue(list.get(i).getFactoryName());
            cell1.setCellStyle(cellStyles[4]);

//            工厂交期	船期	贸易条款
            cell1 = row2.createCell(6);
            cell1.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(list.get(i).getDeliveryPeriod()));
            cell1.setCellStyle(cellStyles[5]);

            cell1 = row2.createCell(7);
            cell1.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(list.get(i).getShipTime()));
            cell1.setCellStyle(cellStyles[6]);

            cell1 = row2.createCell(8);
            cell1.setCellValue(list.get(i).getTradeTerms());
            cell1.setCellStyle(cellStyles[7]);
        }
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);
        downloadUtil.download(byteArrayOutputStream,response,"出货表.xlsx");
    }



    @RequestMapping(value = "/printExcel2",name = "使用模板导出数据到excel")
    public void printExcel2(String inputDate) throws IOException {
        List<ContractProductVo> list=contractService.findByInputDateAndCompanyId(inputDate,getCompanyId());
        SXSSFWorkbook workbook = new SXSSFWorkbook();
        SXSSFSheet sheetAt = workbook.createSheet();
        SXSSFRow row1 = sheetAt.createRow(0);
        //SXSSFCell cell = row1.getCell(1);
        //cell.setCellValue(inputDate.replaceAll("-0","年").replaceAll("-","年")+"月份出货表");
        SXSSFRow row2=null;        //第三行之后
        SXSSFCell cell1=null;
        for (int i = 0; i < list.size(); i++) {
            for (int i1 = 0; i1 < 6000; i1++) {
                row2 = sheetAt.createRow(i + 3);
                cell1 = row2.createCell(1);
                cell1.setCellValue(list.get(i).getCustomName());

                cell1 = row2.createCell(2);
                cell1.setCellValue(list.get(i).getContractNo());

                cell1 = row2.createCell(3);
                cell1.setCellValue(list.get(i).getProductNo());

                cell1 = row2.createCell(4);
                cell1.setCellValue(list.get(i).getCnumber());

                cell1 = row2.createCell(5);
                cell1.setCellValue(list.get(i).getFactoryName());

//            工厂交期	船期	贸易条款
                cell1 = row2.createCell(6);
                cell1.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(list.get(i).getDeliveryPeriod()));

                cell1 = row2.createCell(7);
                cell1.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(list.get(i).getShipTime()));

                cell1 = row2.createCell(8);
                cell1.setCellValue(list.get(i).getTradeTerms());
            }
        }
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);
        downloadUtil.download(byteArrayOutputStream,response,"出货表.xlsx");
    }
}
